import {
  _decorator,
  Component,
  Node,
  Sprite,
  UITransform,
  Animation,
  AnimationClip,
  animation,
  Vec3,
  SpriteFrame,
  debug,
} from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManage'
import ResourceManage from '../Runtime/resourceManage'
import {
  CONTROLLER_ENUM,
  DIRECTION_ENUM,
  DIRECTION_ORDER_ENUM,
  ENTITY_STATE_ENUM,
  ENTITY_TYPE_ENUM,
  EVENT_ENUM,
  PARAMS_NAME_ENUM,
} from '../Enums'
import EventManage from '../Runtime/eventManage'
import { WoodenSkeletonStateMachine } from './WoodenSkeletonStateMachine'
import { EntityManage } from '../Base/EntityManage'
import DataManage from '../Runtime/dataManage'
import { EnemyManage } from '../Base/EnemyManage'
const { ccclass, property } = _decorator

@ccclass('WoodenSkeletonManage')
export class WoodenSkeletonManage extends EnemyManage {
  async init(params) {
    // 初始化人物动画状态机
    this.fsm = this.addComponent(WoodenSkeletonStateMachine)
    await this.fsm.init()
    super.init(params)
    // 监听玩家移动，改变敌人朝向
    EventManage.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack, this)
  }
  onDestroy() {
    super.onDestroy()
    EventManage.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack)
  }
  onAttack() {
    if (this.state === ENTITY_STATE_ENUM.DEATH) return
    const { x: playerX, y: playerY } = DataManage.Instance.player
    // 如果玩家在敌人前后左右四个格子上，就触发攻击状态
    if (
      (playerX === this.x && Math.abs(playerY - this.y) <= 1) ||
      (playerY === this.y && Math.abs(playerX - this.x) <= 1)
    ) {
      this.state = ENTITY_STATE_ENUM.ATTACK
      EventManage.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
    } else {
      this.state = ENTITY_STATE_ENUM.IDLE
    }
  }
}
